package net.mingsoft.base;

import java.security.*;
import java.net.*;
import java.util.jar.*;
import java.io.*;

public class MSVersion
{
    public static String getVersion() {
        return determineSpringBootVersion();
    }
    
    private static String determineSpringBootVersion() {
        final Package pkg = MSVersion.class.getPackage();
        if (pkg != null && pkg.getImplementationVersion() != null) {
            return pkg.getImplementationVersion();
        }
        final CodeSource codeSource = MSVersion.class.getProtectionDomain().getCodeSource();
        if (codeSource == null) {
            return null;
        }
        final URL codeSourceLocation = codeSource.getLocation();
        try {
            final URLConnection connection = codeSourceLocation.openConnection();
            if (connection instanceof JarURLConnection) {
                return getImplementationVersion(((JarURLConnection)connection).getJarFile());
            }
            try (final JarFile jarFile = new JarFile(new File(codeSourceLocation.toURI()))) {
                return getImplementationVersion(jarFile);
            }
        }
        catch (Exception ex) {
            return null;
        }
    }
    
    private static String getImplementationVersion(final JarFile jarFile) throws IOException {
        return jarFile.getManifest().getMainAttributes().getValue(Attributes.Name.IMPLEMENTATION_VERSION);
    }
}
